//
//  JCLNetWorkTools+Extension.swift
//  WeiBo
//
//  Created by DDC on 2017/9/11.
//  Copyright © 2017年 DDC. All rights reserved.
//

import Foundation

// MARK: - 针对本项目对网络工具类做的扩展
extension JCLNetWorkTools {
    
    func statusList(since_id:Int64 = 0,max_id:Int64 = 0, completion:@escaping (_ list:[[String:Any]]?,_ isSuccess:Bool)->())  {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let params = ["since_id":"\(since_id)","max_id":["\(max_id > 0 ? max_id - 1 : 0 )"]] as [String : Any]

        //抽取token加载网络请求的方法
        requestToken(method: .GET, URLString: urlString, parameters: params) { (_ json: Any, _ isSuccess: Bool) in
            if isSuccess {
                let result = json as! NSDictionary
                let resultDict = result["statuses"]
                
                completion(resultDict as? [[String : Any]]  , true)
//                print(json)
            }
        }
        
    }
    
    
    /// 更新未读微博数量方法
    func unreadCount(completion:@escaping (_ count: Int)->())  {
        
        guard let uid = userAccount.uid else {
            return
        }
        
        ///这是测试url  待身份审核通过之后再来更新
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let parmas = ["uid" : uid] as [String:Any]
        requestToken(method: .GET, URLString: urlString, parameters: parmas) { (json, isSuccess) in
            
            let dict = json as? [String: Any]
            let count = dict?["stauts"] as? Int
            
            completion(count ?? 0)
            
        
            
        }
    }
    
}

// MARK: - 处理OAuth授权
extension JCLNetWorkTools {
    
    //登录成功 完成回调
    func loadAccessToken (code :String, completion:@escaping (_ isSuccess:Bool)->()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id":JCLAppID,
                      "client_secret":JCLAppSecret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri":JCLRedirectURI]
        
        request(method: .POST, URLString: urlString, parameters: params) { (json, isSuccess) in
            
            if isSuccess {
                //字典转模型--token ,uid, expires信息
                self.userAccount.yy_modelSet(with: (json as? [String:Any]) ?? [:])
                
                //用户登录后加载当前用户信息
                self.loadUserInfo(completion: { (dict) in
                    print(dict)
                    // 用户名,用户头像
                     self.userAccount.yy_modelSet(with: dict)
                    //保存数据到本地
                    self.userAccount.saveAccount()
                    
//                     print(self.userAccount)
                    //完成回调
                     completion(isSuccess)
                    
                })
            }
        }
        
    }
    
} 

extension JCLNetWorkTools {
    
    func loadUserInfo (completion:@escaping (_ dict:[String:Any])->()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        guard let uid = userAccount.uid else {
            return
        }
        let parms = ["uid":uid]
        
        requestToken(URLString: urlString, parameters: parms) { (json, isSuccess) in
            
            completion((json as? [String:Any]) ?? [:])
        }
        
    }
}

// MARK: - 发布微博
extension JCLNetWorkTools {
    
    func postStatus(text:String, image:UIImage?, completion:@escaping (_ result:[String:Any],_ isSuccess:Bool)->()) {
        // urlString
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        // 发布的微博文本
        let params = ["status":text]
        
        var name:String?
        var data:Data?
        // 文件上传
        if image != nil {
            name = "pic"
            data = UIImagePNGRepresentation(image!)
            
        }
        
        // 获取token来发布
        requestToken(method: .POST, URLString: urlString, parameters: params, name: name, data: data) { (json, isSuccess) in
            completion((json as? [String:Any])!, isSuccess)
        }

        
    }
}




